import request from '../../common/request';

import {wlq_order} from '../../common/config';

Page({
  data:{
    IsActive:0,
    orderList:[],
    // 页数
    page:1,
    // 状态
    state:0,
    // 没有数据加载
    isEnd:false
  },

  // 发送请求的函数
  async getOrderList(page=1,state=0){
    let {orderList} =  this.data;

    const token = wx.getStorageSync('cookie');
    const URL = `${wlq_order}/order/list/${page}?access_token=${token}&type=1&state=${state}`;

    const res = await request(URL);

    console.log('待处理订单列表',res);

    if(res.code===200){
      const temp = [...orderList,...res.data]
      if(res.data.length === 0){
        this.setData({
          isEnd:true
        })
      }
      this.setData({
        orderList:temp
      })
    }

    
  },

  // 获取待处理订单
  handleOrder(){
    let {page,state} = this.data;
    page = 1;
    state = 0;
    this.setData({
      IsActive:0,
      page,
      orderList:[],
      isEnd:false,
      state:0
    })
    this.getOrderList(page,state);

  },

  // 待完成
  handleHandle(){
    let {page,state} = this.data;
    page = 1;
    state = 1;

    // 卖家确定是否已订单已完成
    this.setData({
      IsActive:1,
      state,
      page,
      orderList:[],
      isEnd:false

    })
    this.getOrderList(page,state);

  },

  // 已拒绝
  handleCancel(){

    let {page,state} = this.data;

    page = 1;
    state = 3;

    this.setData({
      IsActive:2,
      state,
      page,
      orderList:[],
      isEnd:false

    })
    this.getOrderList(page,state);

  },

  // 已完成
  handleFinish(){
    let {page,state} = this.data;
    page = 1;
    state = 4;
    this.setData({
      IsActive:3,
      state,
      page,
      orderList:[],
      isEnd:false
    })
    this.getOrderList(page,state);

  },

  onLoad(){
    // 初次加载数据
    this.getOrderList();
  },

  // 接收订单拒绝订单完成订单
  async buttonOrders(e){
    console.log(e.currentTarget.dataset);

    const  orderId = e.currentTarget.dataset.id;

    // 希望之后的状态
    const state = e.currentTarget.dataset.state;

    let {orderList} =  this.data;
    const token =wx.getStorageSync('cookie');

    const URL = `${wlq_order}/order?access_token=${token}`;
    const res = await request(URL,'PUT',JSON.stringify({
      orderId,
      state
    }))
    console.log('处理订单相关',res)
    if(res.code === 200){
      const index = orderList.findIndex(item=>item.orderId === orderId);
      orderList.splice(index,1);
      this.setData({
        orderList
      })
    }
  },

  // 触底加载更多数据
  getMoreOrder(){
    // isEnd为true表示没有更多数据可以加载了
    if(this.data.isEnd){
      return;
    }
    let {page,state} = this.data;
    page++;
    console.log('触底加载更多数据',page,state);

    this.getOrderList(page,state);
    this.setData({
      page
    })
  },

  // 跳转到商品详情页
  navToGoodsDetail(e){
    wx.navigateTo({
      url: `/pages/goods_detail/goods_detail?goodsId=${e.currentTarget.dataset.id}`,
    });
  }
})